package com.atguigu.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import com.atguigu.oss.service.OssService;
import com.atguigu.oss.utils.ConstantPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @ClassName OssServiceImpl
 * @Description TODO
 * @Detail detail
 * @Author MyPC
 * @Date 2020/6/21
 * @Version 1.0
 */
@Service
public class OssServiceImpl implements OssService{
    @Override
    public String uploadAvatarFile(MultipartFile file) {
        InputStream inputStream = null;
        OSS ossClient=null;
        try {
            String endpoint = ConstantPropertiesUtils.END_POINT;
            String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
            String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
            String bucketName = ConstantPropertiesUtils.BUCKET_NAME;
            // 创建OSSClient实例。
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            //获取文件输入流
            inputStream = file.getInputStream();
            String fileName = file.getOriginalFilename();
            //文件名前加上随机值，保证每次上传的文件都是唯一的，防止被覆盖
            String uuid = UUID.randomUUID().toString().replace("-", "");
            //创建图片存储目录，以日期形式创建目录,oss会把yyyy/MM/dd/格式转成目录
            String datePath = new DateTime().toString("yyyy/MM/dd");
            //新的文件名
            fileName=datePath+"/"+uuid+fileName;
            //把文件名称作为文件名称
            ossClient.putObject(bucketName, fileName, inputStream);
            //图片访问路径
            String url="https://"+bucketName+"."+endpoint+"/"+fileName;
            return url;
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(inputStream != null){
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 关闭OSSClient。
            if(ossClient !=null){
                ossClient.shutdown();
            }
        }
        return null;
    }
}
